var express = require('express');
var bodyParser = require("body-parser");
var app = express();
var mysql = require('mysql');
var connection = mysql.createPool({
    connectionLimit : 10,
    host   : 'localhost',
    user   : 'root',　　//数据库登陆就名
    password : '123456', //数据库登陆密码
    database : 'ldkj' //数据库名
});
//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//查询user
app.get('/listUsers', function (req, res) {
    connection.query('select * from admin', function(err, rows, fields) {
        if (err) throw err;
        var data = {code:'200',code_decoration:'查询成功'};
        data.order = rows;
        res.send(data);
    })
});

//增加user
app.post('/adduser', function(req, res){
    console.log(req.body);
    var param = req.body || req.params;
    connection.query('insert into admin(username, password, fullname) values(?,?,?)', [param.username,param.password,param.fullname], function(err, result) {
        if (err){
            throw err;
        }else{
            var data = {code:'200',code_decoration:'添加成功'};
            res.send(data);
        }
    });
});

//删出user
app.post('/delUser', function (req, res) {
    var id = req.body.id || req.params.id;
    console.log(id);
    connection.query("delete from admin where id=" + id, function (err, rows) {
        if (err) {
            var data = '删除失败：' + er
            res.send(data);

        } else {
            var data = {code:'200',code_decoration:'删除成功'};
            res.send(data);
        }
    });
});

//update user
app.post('/updateUser', function (req, res) {
    var param = req.body || req.params;
    console.log(param.username + '--' +param.password);
    connection.query("update admin set password=" + param.password + 'where username=' + param.username, function (err, rows) {
        if (err) {
            res.send('更新失败：' + err);
        } else {
            var data = {code:'200',code_decoration:'更新成功'};
            res.send(data);
        }
    });
});
var server = app.listen(8081, function () {

    console.log("服务启动成功！ http://127.0.0.1:8081/");

})